﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Super
{
	public class LangManager : BaseSingle<LangManager>
	{

		public HashSet<string> keys;
		public List<LangFileInfo> fileList;
		
		public int langIndex = 0;
		[Button("OnRefreshBtnClick")]
		public string refreshBtn = "刷新多语言";

		/// <summary>
		/// 初始化回调接口
		/// </summary>
		public override void OnInit()
		{
			base.OnInit();
			keys = LangUtil.GetKeys();
			fileList = LangUtil.LoadFileList();
			langIndex = GetCurIndex();
		}
		
		/// <summary>
		/// 获取多语言文本的索引
		/// </summary>
		/// <returns></returns>
		public int GetCurIndex()
		{
			return PlayerPrefs.GetInt($"{Application.productName}LangIndex", 0);
		}

		/// <summary>
		/// 设置多语言的索引
		/// </summary>
		/// <param name="index"></param>
		public void SetCurIndex(int index)
		{
			List<LangFileInfo> fileList = Ins.fileList;
			if (0 > index || index >= fileList.Count)
			{
				Debug.Log($"index:{index}越界，LangListCount：{fileList.Count}");
				return;
			}
			else
			{
				PlayerPrefs.SetInt($"{Application.productName}LangIndex", index);
				Ins.langIndex = index;
				Debug.Log($"设置多语言为：{fileList[index].name}");
			}
		}
		
		public void RefreshLangIndex(bool isCustom, string langName)
		{
			for (int i = 0; i < fileList.Count; i++)
			{
				LangFileInfo info = fileList[i];
				if (info.isCustom == isCustom && info.name == langName)
				{
					Ins.langIndex = i;
					Refresh();
					break;
				}
			}
		}

		/// <summary>
		/// 刷新按钮按下回调函数
		/// 设置新的多语言索引
		/// </summary>
		public void OnRefreshBtnClick()
		{
			SetCurIndex(langIndex);
			Refresh();
		}


		/// <summary>
		/// 获取多语言文本
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public string GetText(string key)
		{
			keys ??= LangUtil.GetKeys();
			fileList ??= LangUtil.LoadFileList();
			
			string langText = key;
			string tipInfo = "";
			string tipKey = $"{key}";
			string tipPath = $"<a href=\"{PathSettingSO.Ins.customLangKeyPath}\">文件链接</a>";


			if (string.IsNullOrEmpty(key))//由于Lang组件生成时默认key为空字符，先屏蔽
			{
				//logInfo = "多语言key为空或者空字符不需要翻译，可以不需要Lang或LangFormat脚本";
			}
			else if (langIndex == 0)//默认多语言,直接使用key即可
			{
				if (!keys.Contains(key))
				{
					tipInfo =  $"<color=#{ColorUtility.ToHtmlStringRGB(Color.red)}>{key}</color>不存在，请将相关配置文本添加到{PathSettingSO.Ins.customLangKeyPath}文件中";
				}
			}
			else
			{
				if (!fileList[langIndex].Data.keyValuePairs.TryGetValue(key, out langText))//没有时langText的值为null
				{
					langText = key;
					tipInfo = $"<color=#{ColorUtility.ToHtmlStringRGB(Color.red)}>{key}</color>翻译不存在，请将相关配置文本添加到{LangUtil.GetCurLangPath()}文件中";
					tipPath = $"<a href=\"{LangUtil.GetCurLangPath()}\">文件链接</a>";
				}
			}

			if (!string.IsNullOrEmpty(tipInfo))
			{
				string info = string.Join(Environment.NewLine, tipInfo, tipKey, tipPath);
				Debug.Log(info);
			}

			langText = langText.Replace("\\n", "\n");
			return langText;
		}

		/// <summary>
		/// 添加自定义多语言Key
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public bool TryAddCustomKey(string key)
		{
			keys ??= LangUtil.GetKeys();
			fileList ??= LangUtil.LoadFileList();
			
			if (ValueSettingSO.Ins.CustomLangAddReload)
			{
#if UNITY_EDITOR
				keys = LangUtil.GetKeys();
#endif
			}

			bool isContain = keys.Contains(key);
			if (isContain)
			{
				return false;
			}

			keys.Add(key);
			if (!AssetUtil.AssetExist(PathSettingSO.Ins.customLangKeyPath))
			{
				LangUtil.TryGenerateCustomFile();
			}
			LangUtil.AddKey(key, PathSettingSO.Ins.customLangKeyPath);
			return true;
		}
		
		public void Refresh(bool isCustom, string langName)
		{
			for (int i = 0; i < fileList.Count; i++)
			{
				LangFileInfo info = fileList[i];
				if (info.isCustom == isCustom && info.name == langName)
				{
					langIndex = i;
					Refresh();
					break;
				}
			}
		}

		/// <summary>
		/// 调用所有继承ILangRefresh的MonoBehaviour对象的接口方法，刷新多语言文本
		/// </summary>
		public static void Refresh()
		{
			MonoBehaviour[] monoBehaviours = FindObjectsOfType<MonoBehaviour>();
			foreach (MonoBehaviour monoBehaviour in monoBehaviours)
			{
				if (monoBehaviour is ILangRefresh)
				{
					(monoBehaviour as ILangRefresh)?.OnLangRefresh();
				}
			}
		}
	}
}
